package it.unisalento.appsalento.asynctask;

import it.unisalento.R;
import it.unisalento.appsalento.constants.Constants;
import it.unisalento.appsalento.activity.App;
import it.unisalento.appsalento.activity.fragment.HomeFragment;
import it.unisalento.appsalento.asynctask.framework.MIMETypes;
import it.unisalento.appsalento.bo.mock.MockBo;
import it.unisalento.appsalento.model.GetNewsResponse;
import it.unisalento.appsalento.model.Notizia;
import it.unisalento.appsalento.model.Request;

import java.io.InputStream;
import java.util.ArrayList;

import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.view.MenuItem;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;


/**
 * <p>
 * <b>Description</b>: Classe che estende Async Task. Tale classe si occupa di sincronizzare da WS 
 * le news da visualizzare.
 * </p>
 * @author Gregorio Palama'
 * 
 */
public class NewsAsyncTask extends SyncAsyncTask {
	public NewsAsyncTask(Context context, MenuItem refreshMenuItem) {
		this.context = context;
		this.refreshMenuItem = refreshMenuItem;
	}
	
	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		if (refreshMenuItem != null) {
			if(App.homeFragment != null && App.homeFragment.isVisible()){
				App.homeFragment = new HomeFragment();
				FragmentManager fragmentManager = App.currentActivity().getFragmentManager();
				fragmentManager.beginTransaction().replace(R.id.content_frame, App.homeFragment).commit();
			}
			 refreshMenuItem.collapseActionView();
	         refreshMenuItem.setActionView(null);
		}
		
		Intent intent = new Intent(Constants.UPDATE_NEWS_EVENT);
		if(App.currentActivity() != null){
			LocalBroadcastManager.getInstance(App.currentActivity().getApplicationContext()).sendBroadcast(intent);
		}
				

	}


	/**
	 * Metodo che si occupa di effettuare la chiamata ai WS per ottenere la lista di news.
	 * @param mapper ObjectMapper necessario per la conversione del json restituito in oggetto java.
	 * @return 
	 * <li>true : se la chiamata ai ws �� andata a buon fine</li>
	 * <li>false : se la chiamata ai ws ha restituito un errore o se il parametro status del json di risposta ��
	 * impostato a KO</li>
	 */
	public boolean setData(ObjectMapper mapper)  {
		boolean retVal = false;
		try {
			GetNewsResponse newsResponse = null;
			if(!Constants.MOCK_ENABLED){
				Request request = new Request();
				request.setUtente(App.utente);
				
				final Client client = Client.create();
				final WebResource resource = client.resource(Constants.URL_REST	+ Constants.SERVICE_NEWS);
				final ClientResponse response = resource.type(MIMETypes.APPLICATION_JSON.getName()).post(
						ClientResponse.class, gson.toJson(request));
				if (response.getStatus() != 201 && response.getStatus() != 200) {
					throw new RuntimeException("failed: http error code = "
							+ response.getStatus());
				}
				final String responseEntity = response.getEntity(String.class).replaceAll("\\\\", "");
			    newsResponse = mapper.readValue(responseEntity, GetNewsResponse.class);
			}else{
				InputStream is = context.getAssets().open(MockBo.GET_NEWS_RESPONSE);
				newsResponse = mapper.readValue(is, GetNewsResponse.class);
			}
			if(newsResponse != null){ 
				App.news = new ArrayList<Notizia>();
				if (newsResponse.isOk()) {
					App.news = newsResponse.getNews();
				}
				retVal = newsResponse.isOk();
			}
		} catch (Throwable t) {
			App.news = new ArrayList<Notizia>();
			t.printStackTrace();
		}
		return retVal;
	}
	
}
